//
//  UILabel+Extension.swift
//  Slaughter
//
//  Created by 邱仙凯 on 2021/10/25.
//  Copyright © 2021 aowang. All rights reserved.
//

import UIKit

extension UILabel {
   // label加下划线
    func underline() {
         if let textString = self.text {
             let attributedString = NSMutableAttributedString(string: textString)
             attributedString.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributedString.length))
             attributedText = attributedString
         }
     }
    // 中划线
    func strikeLine() {
        if let textString = self.text {
            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributedString.length))
            attributedText = attributedString
        }
    }
  
    
     /// UILabel根据文字的需要的高度
    public var requiredHeight: CGFloat {
        let label = UILabel(frame: CGRect(
            x: 0,
            y: 0,
            width: frame.width,
            height: CGFloat.greatestFiniteMagnitude)
        )
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        label.font = font
        label.text = text
        label.attributedText = attributedText
        label.sizeToFit()
        return label.frame.height
    }
    /// UILabel根据文字的需要的宽度
    public var requiredWidth: CGFloat {
        let label = UILabel(frame: CGRect(
            x: 0,
            y: 0,
            width:  CGFloat.greatestFiniteMagnitude,
            height: frame.height)
        )
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        label.font = font
        label.text = text
        label.attributedText = attributedText
        label.sizeToFit()
        return label.frame.width
    }
    
    /// UILabel根据文字实际的行数
    public var lines: Int {
        return Int(requiredHeight / font.lineHeight)
    }
     
    
    // 部分高亮  colorText  中文，颜色16进制
    func attributedText(completeString:String,colorText:[(String,UIColor)]) {
        
        let tt = NSMutableAttributedString(string: completeString)
     
        for item in colorText {
            tt.addAttribute(NSAttributedString.Key.foregroundColor, value: item.1, range: (completeString as NSString).range(of: item.0))
        }
      self.attributedText = tt
 
    }
    
    
    
    struct AssociatedBtnKeys{
       static var maxKeyLengthKey = "maxKeyLengthKey"
     }
    
    var maxKeyLength: CGFloat {
        set {
            objc_setAssociatedObject(self, &AssociatedBtnKeys.maxKeyLengthKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        
        get {
            return (objc_getAssociatedObject(self, &AssociatedBtnKeys.maxKeyLengthKey) as? CGFloat) ?? 0
        }
    }
    
 
    func multiLineTitleContentShow(contentStr:String,fontx:CGFloat,color:UIColor = .black) {
      
                let paraph = NSMutableParagraphStyle()
                //将行间距设置为28
                paraph.lineSpacing = 6
     
          
            
                // 假设使用相同的字体来计算空格宽度
                let spaceFont = self.font
                let spaceString = " "
                let spaceAttributes = [NSAttributedString.Key.font: spaceFont]
                let spaceWidth = spaceString.size(withAttributes: spaceAttributes).width
          
                // 分割文本并处理每对键值
                let parts = contentStr.components(separatedBy: "#")
                let attributedString = NSMutableAttributedString()
          
                
                //提前算出最大左边宽度
                for part in parts {
                    guard !part.isEmpty else { continue }
                    let keyValue = part.components(separatedBy: ":")
                    guard keyValue.count >= 2 else { continue }
          
                    let key = keyValue[0].trimmingCharacters(in: .whitespacesAndNewlines)
                    let keyAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontx)]
                    let keySize = key.size(withAttributes: keyAttributes)
                    maxKeyLength = max(maxKeyLength, keySize.width)
                }
                if maxKeyLength < 90 {
                    maxKeyLength = 90
                }
          
        for i in 0..<parts.count {
            let part = parts[i]
                    guard !part.isEmpty else { continue }
                    
                    var keyOri = part.preChar(char: ":").unwrap
                    if keyOri == "" {
                        keyOri = part.preChar(char: "：").unwrap
                    }
     
                    var valueOri = part.replacingOccurrences(of: "\(keyOri)", with: "")
                    if valueOri.count > 0 {
                        valueOri = String(valueOri.dropFirst())// 第一个就是冒号啦
                    }
                    
                  
          
                    var key = keyOri.trimmingCharacters(in: .whitespacesAndNewlines)
                    let keyAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontx),NSAttributedString.Key.foregroundColor: color,NSAttributedString.Key.paragraphStyle: paraph]
                    let keySize = key.size(withAttributes: keyAttributes)
                  
          
                    var value = valueOri.trimmingCharacters(in: .whitespacesAndNewlines)
                    if value == "-" {
                        value = ""
                    }
                    if key == "-" {
                        key = "  "
                    }
          
                    // 计算空格数
                    let spacesCount = Int((maxKeyLength - keySize.width) / spaceWidth)
                    let spacesString = String(repeating: " ", count: spacesCount)
          
                    let fullLine = NSMutableAttributedString()
                    // 把冒号换成空格，有点距离，又符合需求
                    fullLine.append(NSAttributedString(string: key + " ", attributes: keyAttributes))
            if i == parts.count - 1 {
                // 最后一个不再加换行符
                fullLine.append(NSAttributedString(string: spacesString + value, attributes: keyAttributes))
            } else {
                fullLine.append(NSAttributedString(string: spacesString + value + "\n", attributes: keyAttributes))
            }
                    
          
                    attributedString.append(fullLine)
                }
           
          
     
                self.attributedText = attributedString
                
                 
           
        
    }
}
